public class Solution {
    public static int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;

        int[][] dp = new int[m + 1][n + 1];

        //初始化
        for (int i = 0; i < m + 1; i++) {
            for (int j = 0; j < n + 1; j++) {
                dp[0][j] = Integer.MAX_VALUE * (-1);
                dp[i][0] = Integer.MAX_VALUE * (-1);
            }
        }
        dp[0][1] = 0;
        dp[1][0] = 0;


        for (int i = 1; i < m + 1; i++) {
            for (int j = 1; j < n + 1; j++) {
                if (i == 1) {
                    dp[i][j] = dp[i][j- 1] + dungeon[i - 1][j - 1];
                } else if (j == 1) {
                    dp[i][j] = dp[i - 1][j] + dungeon[i - 1][j - 1];
                } else {
                    if ((dp[i][j - 1] < 0 && dp[i - 1][j] < 0) || (dp[i][j - 1] > 0 && dp[i - 1][j] > 0)) {
                        dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]) + dungeon[i - 1][j - 1];
                    } else {
                        dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + dungeon[i - 1][j - 1];
                    }
                }
            }
        }

        int ret = dp[m][n];

        if (ret >= 0) {
            return 1;
        } else {
            return ret * (-1) + 1;
        }
    }

    public int calculateMinimumHP2(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;

        int[][] dp = new int[m + 1][n + 1];

        //初始化
        for (int j = 0; j < n + 1; j++) {
            dp[m][j] = Integer.MAX_VALUE;
        }
        for (int i = 0; i < m + 1; i++) {
            dp[i][n] = Integer.MAX_VALUE;
        }
        dp[m][n - 1] = 1;
        dp[m - 1][n] = 1;

        //从右下角向左上角填写
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                dp[i][j] = Math.min(dp[i][j + 1], dp[i + 1][j]) - dungeon[i][j];
                dp[i][j] = Math.max(1, dp[i][j]);
            }
        }

        return dp[0][0];
    }

    public static void main(String[] args) {
        System.out.println(calculateMinimumHP(new int[][]{{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}));
    }
}
